<?php
//定义一个类
class Db{
    private $host;
    private $root;
    private $pwd;
    private $dbname;
    private $port;
    private $charset;
    public $link;//数据库对象
    public function __construct($params)
    {
        //初始化属性
        $this->init($params);
         //创建数据库对象
         $this->connect();
    }
     //初始化属性
    private function init($params=array()){
        $this->host=$params['host']??'localhost';//isset($params['host'])?$params['host'])?$params['host']:'localhost'
        $this->root=$params['root']??'root';
        $this->pwd=$params['pwd']??'123';
        $this->dbname=$params['dbname'];
        $this->port=$params['port']??'3306';
        $this->charset=$params['$charset']??'utf8';
    }
    //创建数据库对象
    private function connect(){
       $this->link=@mysqli_connect($this->host,$this->root,$this->pwd,$this->dbname,$this->port);
       if(!$this->link){
           echo"数据库连接失败".mysqli_connect_error();
           exit;
       }
       mysqli_set_charset($this->link,$this->charset);
    }
    //执行增删改查
    public function execute($sql){
        if(!$str=mysqli_query($this->link,$sql)){
            echo"sql语句执行错误".mysqli_error($this->link);
            echo "<br>错误的sql语句是".$sql;
            exit;
        }
        return $str;
    }
    //查询
    public function select($sql,$type="num"){
        $result=$this->execute($sql);
        $type=$this->getType($type);
        
        if((mysqli_num_rows($result)>0)){
            // echo $type;
           return mysqli_fetch_all($result,$type);
        }
    }
    //查询返回数组类型
    private function getType($type){
        if($type=='asso'){
            $type=MYSQLI_ASSOC;
        }else if($type=='num'){
            $type=MYSQLI_NUM;
        }else{
            $type=MYSQLI_BOTH;
        }
        return $type;
    }
}


// $str=[
//     "host"=>"127.0.0.1",
//     "root"=>"root",
//     "pwd"=>"root",
//     "dbname"=>"db"
// ];
// $DB=new Db($str);
// $sql="insert into user values ('1','zhangsan','10')";
// $DB->execute($sql);
// var_dump($DB->execute($sql));
// $sql="select * from user";
// var_dump($DB->select($sql));

?>